package com.totoro.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.totoro.pojo.*;
import com.totoro.service.OrderService;
import com.totoro.service.ReturnService;
import com.totoro.utils.Odd;
import com.totoro.utils.ReturnFormat;
import lombok.SneakyThrows;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.List;

/**
 * @author TOTORO
 * @date 2021/8/9 23:40
 * 处理甲方乙方所有的退货款辩论
 */
@Controller
@RequestMapping("/dispute_logic")
public class ReturnController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private ReturnService returnService;

    /**
     * 新增退货款记录
     * @param primaryReturn
     * @param files
     * @param instructions
     * @param marketOdd
     * @param msrId
     * @param session
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/addReturn", method = RequestMethod.POST)
    public String addReturn(PrimaryReturn primaryReturn, @RequestParam(value = "eImages", required = false) MultipartFile[] files, @RequestParam(value = "instruction", required = false) String[] instructions,
                            @RequestParam("bizOrderId") String marketOdd, @RequestParam("detailId") int msrId,
                            HttpSession session, HttpServletRequest request, Model model){
        User user = (User) session.getAttribute("user");
        // 将该详情订单和主订单改为售后状态
        MarketOrder marketOrder = orderService.findAllOrder(marketOdd, 2, 0).get(0);
        // 修改主订单上一次的订单状态
        orderService.updateMarketOrderPrevStatus(marketOrder.getOrderStatus(), marketOrder.getMarketOdd());
        marketOrder.setOrderStatus(6);
        orderService.updateOrder(marketOrder);
        // 添加主订单时间线
        OrderTimeline orderTimeline = new OrderTimeline(0, marketOrder.getId(), marketOrder.getOrderStatus());
        orderService.addOrderTimeLineByMid(orderTimeline);

        // 详情订单
        orderService.updateMarketSrReturnStatus(1, 0, msrId);
        // 先添加一条主要退货款
        // 1、获取退款编号
        primaryReturn.setReturnOdd(Odd.getReturnId(primaryReturn.getReturnType()));
        primaryReturn.setMarketOdd(marketOdd);
        primaryReturn.setMarketSrId(msrId);
        primaryReturn.setReturnStatus(1);
        returnService.addPrimaryReturn(primaryReturn);

        // 添加该状态
        ReturnStatusInfo returnStatusInfo = new ReturnStatusInfo();
        returnStatusInfo.setPrimaryReturnId(primaryReturn.getId());
        returnStatusInfo.setReturnStatus(1);
        returnStatusInfo.setUserReasonText("买家申请了"+(primaryReturn.getReturnType()==0?"退款":"退货款"));
        returnStatusInfo.setSellerReasonText("买家申请了"+(primaryReturn.getReturnType()==0?"退款":"退货款"));
        returnService.addPrimaryReturnAssignStatusInfo(returnStatusInfo);

        // 买家是否上传了图片
        if(files.length > 0){
            returnService.addPrimaryReturnImage(primaryReturn.getId(), primaryReturn.getReturnStatus(), files, instructions, request);
        }

        // 添加一条系统默认的足迹表
        NegotiateHistory negotiateHistory = new NegotiateHistory();
        negotiateHistory.setPrimaryReturnId(primaryReturn.getId());
        negotiateHistory.setSendMessage("发起了"+(primaryReturn.getReturnStatus()==0?"退款":"退货退款")
                        +"申请，原因："+primaryReturn.getReturnReason()+"，金额："
                +primaryReturn.getReturnMoney()+"元"+(primaryReturn.getReturnDetail().equals("")?"":"，说明："+primaryReturn.getReturnDetail()));
        negotiateHistory.setSendBy(0);
        negotiateHistory.setUid(user.getUserId());
        returnService.addNegotiateHistory(negotiateHistory);

        return "redirect:/dispute/detail.htm?bizOrderId="+marketOrder.getMarketOdd()+"&detailId="+msrId+"&bizReturnId="+primaryReturn.getReturnOdd();
    }

    /**
     * 修改申请
     * @param primaryReturn
     * @param files
     * @param instructions
     * @param originalImageId
     * @param originalInstruction
     * @param session
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/updateReturn")
    public String updateReturnApply(PrimaryReturn primaryReturn, @RequestParam(value = "eImages", required = false) MultipartFile[] files,
                                    @RequestParam(value = "instruction", required = false) String[] instructions,
                                    /** 以下两个是用来判断之前的图片是否删除，因为file-input只是可读的，不能动态的修改值 */
                                    @RequestParam(value = "originalImageId", required = false) Integer[] originalImageId,
                                    @RequestParam(value = "originalInstruction", required = false) String[] originalInstruction,
                                    HttpSession session, HttpServletRequest request, Model model){
        User user = (User) session.getAttribute("user");
        primaryReturn.setReturnStatus(1);
        // 拿到最新的退货款单
        PrimaryReturn truePrimaryReturn = returnService.findPrimaryReturnAllDetailByReturnOdd(primaryReturn.getReturnOdd());
        // 先改变主要退货款单
        returnService.updatePrimaryReturn(primaryReturn);
        // 如果那边都删除了原有的，则这边io在文件里也都删除掉
        if(originalImageId == null || originalImageId.length < 1) {
            if (truePrimaryReturn.getPrtImages() != null && truePrimaryReturn.getPrtImages().size() > 0) {
                String uploadPath = request.getSession().getServletContext().getRealPath("/");
                for (PrtImages prtImage : truePrimaryReturn.getPrtImages()) {
                    File file = new File(uploadPath + prtImage.getImagePath());
                    if (file.exists()) {
                        file.delete();
                    }
                }
            }
        } else{
            // 只删除个别的
            List<PrtImages> prtImages = returnService.findShallQuiltRemoveMultipleImage(truePrimaryReturn.getId(), originalImageId);
            if(prtImages.size() > 0){
                String uploadPath = request.getSession().getServletContext().getRealPath("/");
                for (PrtImages prtImage : prtImages) {
                    File file = new File(uploadPath + prtImage.getImagePath());
                    if (file.exists()) {
                        file.delete();
                    }
                }
            }
        }

        // 图片删除更改思路
        // 如果用户把所有的原有图片都删除了，则全部删除，否则只删除原有图片之外的该退货款单1级图片
        if(originalImageId == null || originalImageId.length < 1) {
            returnService.deletePrimaryReturnAssignStatusImages(primaryReturn.getId(), 1);
        } else{
            returnService.deletePrimaryReturnOneStatusImages(truePrimaryReturn.getId(), originalImageId);
            for (int i = 0; i < originalImageId.length; i++) {
                returnService.updatePrimaryReturnAssignStatusImageInstructionByImageId(originalImageId[i], originalInstruction[i]);
            }
        }

        // 如果用户携带了图片，则重新添加
        if(files.length > 0){
            returnService.addPrimaryReturnImage(primaryReturn.getId(), primaryReturn.getReturnStatus(), files, instructions, request);
        }
        // 添加一条修改申请的协商表
        NegotiateHistory negotiateHistory = new NegotiateHistory();
        negotiateHistory.setPrimaryReturnId(primaryReturn.getId());
        negotiateHistory.setSendMessage("修改了"+(primaryReturn.getReturnStatus()==0?"退款":"退货退款")+"申请。");
        negotiateHistory.setSendBy(0);
        negotiateHistory.setUid(user.getUserId());
        returnService.addNegotiateHistory(negotiateHistory);

        return "redirect:/dispute/detail.htm?bizOrderId="+truePrimaryReturn.getMarketOdd()+"&detailId="+truePrimaryReturn.getMarketSrId()+"&bizReturnId="+truePrimaryReturn.getReturnOdd();
    }

    /**
     * 撤销申请
     * @param returnId
     * @param session
     * @return
     */
    @RequestMapping(value = "/withdrawReturn", method = RequestMethod.POST)
    @ResponseBody
    public String withdrawReturn(@RequestParam("bizReturnId") String returnId, HttpSession session){
        User user = (User) session.getAttribute("user");
        PrimaryReturn primaryReturn = returnService.findPrimaryReturnAllDetailByReturnOdd(returnId);
        // 买家撤销申请，需要从以下几个方面做出改变
        // 1、修改该详情订单的正在售后中，和是否售后过的状态
        // 2、修改退货款主订单的退货款状态为售后关闭
        // 3、新增一条售后关闭状态的原因为 ： 买家自动撤销
        // 4、新增一条系统给出的协商记录： 买家自动撤销

        // (1)
        orderService.updateMarketSrReturnStatus(0, 0, primaryReturn.getMarketSrId());
        // (2)
        primaryReturn.setReturnStatus(26);
        returnService.updatePrimaryReturnStatusByReturnOdd(primaryReturn);
        // (3)
        ReturnStatusInfo returnStatusInfo = new ReturnStatusInfo();
        returnStatusInfo.setPrimaryReturnId(primaryReturn.getId());
        returnStatusInfo.setReturnStatus(26);
        returnStatusInfo.setUserReasonText("因您撤销退款申请，退款已关闭，交易将正常进行。请关注交易超时");
        returnStatusInfo.setSellerReasonText("买家已撤销退款申请，退款已关闭，交易正常进行");
        returnService.addPrimaryReturnAssignStatusInfo(returnStatusInfo);
        // (4)
        NegotiateHistory negotiateHistory = new NegotiateHistory();
        negotiateHistory.setPrimaryReturnId(primaryReturn.getId());
        negotiateHistory.setSendBy(0);
        negotiateHistory.setSendMessage("买家撤销退款申请，退款已关闭，交易将正常进行");
        negotiateHistory.setUid(user.getUserId());
        returnService.addNegotiateHistory(negotiateHistory);
        // 保存参数，返回退款货款详情页
        return "/dispute/detail.htm?bizOrderId="+primaryReturn.getMarketOdd()+"&detailId="+primaryReturn.getMarketSrId()+"&bizReturnId="+primaryReturn.getReturnOdd();
    }


    /**
     * 买家确认发货
     * @param returnId
     * @param session
     * @return
     */
    @RequestMapping(value = "/buyerShip", method = RequestMethod.POST)
    @ResponseBody
    public String buyerShip(@RequestParam("bizReturnId") String returnId, HttpSession session){
        User user = (User) session.getAttribute("user");
        // 拿到最新的改单记录
        PrimaryReturn primaryReturn = returnService.findPrimaryReturnAllDetailByReturnOdd(returnId);
        // 买家已发货，需要修改退货款状态为买家已发货
        // 2、新增一条买家发货的状态详情
        // 3、新增一条买家发货的系统协商
        // (1)
        primaryReturn.setReturnStatus(23);
        returnService.updatePrimaryReturnStatusByReturnOdd(primaryReturn);
        // (2)
        ReturnStatusInfo returnStatusInfo = new ReturnStatusInfo();
        returnStatusInfo.setPrimaryReturnId(primaryReturn.getId());
        returnStatusInfo.setReturnStatus(23);
        returnStatusInfo.setUserReasonText("您已发货，等待卖家收货...");
        returnStatusInfo.setSellerReasonText("买家已发货，请关注物流信息，进行收货操作...");
        returnService.addPrimaryReturnAssignStatusInfo(returnStatusInfo);
        // (3)
        NegotiateHistory negotiateHistory = new NegotiateHistory();
        negotiateHistory.setPrimaryReturnId(primaryReturn.getId());
        negotiateHistory.setSendBy(0);
        negotiateHistory.setSendMessage("买家已发货，等待卖家收货");
        negotiateHistory.setUid(user.getUserId());
        returnService.addNegotiateHistory(negotiateHistory);
        // 保存参数，返回退款货款详情页
        return "/dispute/detail.htm?bizOrderId="+primaryReturn.getMarketOdd()+"&detailId="+primaryReturn.getMarketSrId()+"&bizReturnId="+primaryReturn.getReturnOdd();
    }


    @SneakyThrows
    @RequestMapping(value = "/findTermBuyerDisputeListData", method = RequestMethod.POST)
    @ResponseBody
    public String findTermBuyerDisputeListData(@RequestParam("jsonString") String jsonString, HttpSession session){
        JsonNode jsonNode = new ObjectMapper().readTree(jsonString);
        int type = jsonNode.get("type").asInt();
        int time = jsonNode.get("time").asInt();
        int status = jsonNode.get("status").asInt();
        String startTime = jsonNode.get("startTime").asText();
        String endTime = jsonNode.get("endTime").asText();

        User user = (User) session.getAttribute("user");
        if(null == user){
            return ReturnFormat.retData("session会话过期", false);
        }
        List<PrimaryReturn> primaryReturns = returnService.findUserReturnList(user.getUserId(), type, time, status, startTime, endTime);
        return ReturnFormat.retData(primaryReturns, true);
    }

    /** 以下为公共的操作 -------------------------------------- */

    /**
     * 保存上一次对策参数
     * @param bizOrderId
     * @param detailId
     * @param bizReturnId
     * @param session
     * @return
     */
    @RequestMapping("/saveBeforeParam")
    @ResponseBody
    public String saveBeforeParam(@RequestParam("bizOrderId") String bizOrderId, @RequestParam("detailId") int detailId,
                                  @RequestParam("bizReturnId") String bizReturnId,HttpSession session){
        session.setAttribute("bizOrderId", bizOrderId);
        session.setAttribute("detailId", detailId);
        session.setAttribute("bizReturnId", bizReturnId);
        System.out.println("保存成功");
        return "success";
    }

    /**
     * 增加一条协商记录
     * @param primaryReturnId
     * @param negotiateHistoryText
     * @param files
     * @param instructions
     * @param session
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/addNegotiateHistory")
    public String addNegotiateHistory(@RequestParam("primaryReturnId") int primaryReturnId, @RequestParam("sendBy") int sendBy,
                                      @RequestParam("negotiateHistoryText") String negotiateHistoryText,
                                      @RequestParam(value = "eImages", required = false) MultipartFile[] files, @RequestParam(value = "instruction", required = false) String[] instructions,
                                      @RequestParam(value = "isRefuse", required = false, defaultValue = "0") int isRefuse,
                                      HttpSession session, HttpServletRequest request, Model model){
        User user = (User) session.getAttribute("user");
        // 添加一条协商记录，以用户 或 卖家 发送
        NegotiateHistory negotiateHistory = new NegotiateHistory(0, primaryReturnId, negotiateHistoryText, sendBy, user.getUserId(), null, null);
        returnService.addNegotiateHistory(negotiateHistory);

        // 是否上传了图片
        if(files.length > 0){
            returnService.addNegotiateHistoryImage(negotiateHistory.getId(), files, instructions, request);
        }
        // 拿到保存的参数
        String bizOrderId = (String) session.getAttribute("bizOrderId");
        Integer detailId = (Integer) session.getAttribute("detailId");
        String bizReturnId = (String) session.getAttribute("bizReturnId");
        // 据不同人返不同页
        if(sendBy == 0){
            return "redirect:/dispute/detail.htm?bizOrderId="+bizOrderId+"&detailId="+detailId+"&bizReturnId="+bizReturnId;
        } else{
            // 如果是卖家的拒绝售后
            if(isRefuse == 1){
                return "redirect:/seller/dispute/sellerRefuseDispute.htm?bizOrderId="+bizOrderId+"&detailId="+detailId+"&bizReturnId="+bizReturnId;
            }
            return "redirect:/seller/dispute/detail.htm?bizOrderId="+bizOrderId+"&detailId="+detailId+"&bizReturnId="+bizReturnId;
        }
    }







//    以下为卖家方 操作-------------------------------------------------

    /**
     * 同意本次退货款单
     * @param returnId
     * @param session
     * @return
     */
    @RequestMapping(value = "/agreeSaleAfter", method = RequestMethod.POST)
    @ResponseBody
    public String agreeSaleAfter(@RequestParam("bizReturnId") String returnId, HttpSession session){
        User user = (User) session.getAttribute("user");
        // 获得本次退货款单
        PrimaryReturn primaryReturn = returnService.findPrimaryReturnAllDetailByReturnOdd(returnId);
        int status = primaryReturn.getReturnType()==0?11:21;
        primaryReturn.setReturnStatus(status);
        returnService.updatePrimaryReturnStatusByReturnOdd(primaryReturn);
        // 增加一条该状态的详情
        ReturnStatusInfo returnStatusInfo = new ReturnStatusInfo();
        returnStatusInfo.setPrimaryReturnId(primaryReturn.getId());
        returnStatusInfo.setReturnStatus(status);
        String userReason = primaryReturn.getReturnType()==0?"商家同意了您的申请，本次售后已结束，金额将按照付款方式返还":"商家同意了您的退货申请，请尽快联系商家进行退货";
        returnStatusInfo.setUserReasonText(userReason);
        returnStatusInfo.setSellerReasonText("商家同意了买家申请的"+(primaryReturn.getReturnType()==0?"退款":"退货款")+"请求");
        returnService.addPrimaryReturnAssignStatusInfo(returnStatusInfo);
        // 如果只是退款，则直接修改主订单状态为订单结束，将详表售后中状态改完售后完成，已售后
        if(primaryReturn.getReturnType() == 0){
            // 1、先获得主订单
            MarketOrder marketOrder = orderService.findAllOrder(primaryReturn.getMarketOdd(), 2, 0).get(0);
            marketOrder.setOrderStatus(7);
            orderService.updateOrder(marketOrder);
            // 2、修改详情订单
            orderService.updateMarketSrReturnStatus(0, 1, primaryReturn.getMarketSrId());
        }
        // 添加一条历史协商
        NegotiateHistory negotiateHistory = new NegotiateHistory(0, primaryReturn.getId(), returnStatusInfo.getSellerReasonText(), 1, user.getUserId(), null, null);
        returnService.addNegotiateHistory(negotiateHistory);
        // 返回
        return "/seller/dispute/detail.htm?bizOrderId="+primaryReturn.getMarketOdd()+"&detailId="+primaryReturn.getMarketSrId()+"&bizReturnId="+primaryReturn.getReturnOdd();
    }

    /**
     * 拒绝本次退货款
     * @param returnId
     * @param reason
     * @param session
     * @return
     */
    @RequestMapping(value = "/refuseSaleAfter", method = RequestMethod.POST)
    public String sellerRefuseSaleAfter(@RequestParam("bizReturnId") String returnId,
                                        @RequestParam(value = "eImages", required = false) MultipartFile[] files,
                                        @RequestParam(value = "instruction", required = false) String[] instructions,
                                        @RequestParam("reason")String reason, @RequestParam("detail") String detail, HttpSession session,
                                        HttpServletRequest request){
        User user = (User) session.getAttribute("user");
        // 获得本次id
        PrimaryReturn primaryReturn = returnService.findPrimaryReturnAllDetailByReturnOdd(returnId);
        int status = primaryReturn.getReturnType()==0?12:22;
        // 卖家拒绝了，修改该退货款单号状态
        primaryReturn.setReturnStatus(status);
        returnService.updatePrimaryReturnStatusByReturnOdd(primaryReturn);
        // 添加本次退货款的22或者12拒绝状态原因
        // 创建对象进行修改
        ReturnStatusInfo returnStatusInfo = new ReturnStatusInfo();
        returnStatusInfo.setPrimaryReturnId(primaryReturn.getId());
        returnStatusInfo.setReturnStatus(status);
        String userReason = "商家拒绝了本次"+(primaryReturn.getReturnType()==0?"退款":"退货款")+"的申请，本次售后结束，买家可协同商家，进行再次申请";
        returnStatusInfo.setUserReasonText(userReason);
        returnStatusInfo.setSellerReasonText(reason +"&" +detail);
        returnService.addPrimaryReturnAssignStatusInfo(returnStatusInfo);
        // 添加一条拒绝的协商记录
        NegotiateHistory negotiateHistory = new NegotiateHistory(0, primaryReturn.getId(), userReason, 1, user.getUserId(), null, null);
        returnService.addNegotiateHistory(negotiateHistory);
        // 被拒绝，那么修改主订单的状态为之前保存的状态，修改详情订单为 不在售后中0 没有进行过售后0 ，因为被拒绝还有权力继续
        // 1、先获得主订单
        MarketOrder marketOrder = orderService.findAllOrder(primaryReturn.getMarketOdd(), 2, 0).get(0);
        marketOrder.setOrderStatus(marketOrder.getPrevStatus());
        orderService.updateOrder(marketOrder);
        // 2、修改详情订单
        orderService.updateMarketSrReturnStatus(0, 0, primaryReturn.getMarketSrId());
        // 如果有图片，则添加图片
        if(files.length > 0){
            returnService.addPrimaryReturnImage(primaryReturn.getId(), status, files, instructions, request);
        }
        // 跳转
        return "redirect:/seller/dispute/detail.htm?bizOrderId="+primaryReturn.getMarketOdd()+"&detailId="+primaryReturn.getMarketSrId()+"&bizReturnId="+primaryReturn.getReturnOdd();
    }


    /**
     * 确认退货款
     * @param returnId
     * @param session
     * @return
     */
    @RequestMapping(value = "/confirmReceiptOrReimburse", method = RequestMethod.POST)
    @ResponseBody
    public String confirmReceiptOrReimburse(@RequestParam("bizReturnId") String returnId, HttpSession session){
        User user = (User) session.getAttribute("user");
        // 获得本次id
        PrimaryReturn primaryReturn = returnService.findPrimaryReturnAllDetailByReturnOdd(returnId);
        // 拿到本次类型，判断是退款还是退货款
        int status  = primaryReturn.getReturnType() == 0?11:25;
        String msg = primaryReturn.getReturnType()==0?"商家同意了本次退款，交易已关闭":"商家已收到货，同意了本次退货款，交易已关闭";
        // 确认收货，将本次退货单改成退货款完成，增加原因，协商记录
        primaryReturn.setReturnStatus(status);
        returnService.updatePrimaryReturnStatusByReturnOdd(primaryReturn);
        // 添加本次退货款的22或者12拒绝状态原因
        // 创建对象进行修改
        ReturnStatusInfo returnStatusInfo = new ReturnStatusInfo();
        returnStatusInfo.setPrimaryReturnId(primaryReturn.getId());
        returnStatusInfo.setReturnStatus(status);
        returnStatusInfo.setUserReasonText(msg);
        returnStatusInfo.setSellerReasonText(msg);
        returnService.addPrimaryReturnAssignStatusInfo(returnStatusInfo);
        // 添加一条拒绝的协商记录
        NegotiateHistory negotiateHistory = new NegotiateHistory(0, primaryReturn.getId(), msg, 1, user.getUserId(), null, null);
        returnService.addNegotiateHistory(negotiateHistory);
        // 修改主订单和详情订单
        // 1、先获得主订单
        MarketOrder marketOrder = orderService.findAllOrder(primaryReturn.getMarketOdd(), 2, 0).get(0);
        marketOrder.setOrderStatus(7);
        orderService.updateOrder(marketOrder);
        // 2、修改详情订单
        orderService.updateMarketSrReturnStatus(0, 1, primaryReturn.getMarketSrId());
        // 跳转
        return "/seller/dispute/detail.htm?bizOrderId="+primaryReturn.getMarketOdd()+"&detailId="+primaryReturn.getMarketSrId()+"&bizReturnId="+primaryReturn.getReturnOdd();
    }
}
